from python_depend.redis_pool import RedisPoolManager
from python_depend.tidb_data_query import fetch_spx_stock_list, fetch_all_stock_list

from python_depend.time_urtils import get_current_date, is_within_num_days
from python_depend.workflow_api import work_flow_cache_call, work_flow_cache_delete, work_flow_cache_refresh

# ==============================
# redis初始化
# ==============================
redis_key_stock = "ds:tech_indicator:all_pattern:"
RedisPoolManager.initialize()
redis_client = RedisPoolManager.get('default')


def executor_data_cache(code, error_code_list):
    date = get_current_date()
    fee_flag_list = fee_flag.split(",")
    # 0表示免费，1表示付费,收费和付费各缓存一次
    for flag in fee_flag_list:
        # 缓存日期为今天则缓存过,跳过
        redis_key = redis_key_stock + flag + ":" + str(code)
        print(f"redis key is {redis_key}")
        cacheData = redis_client.get(redis_key)
        if cacheData is not None and is_within_num_days(cacheData, date, 1) and forced_refresh_flag != "1":
            print(f"缓存日期：{cacheData},{code}，收费标记：{flag}，已缓存数据")
            continue
        input_variable_values = {
            "elements": {"name": "all_pattern", "category": "pattern"},
            "ticker": code,
            "fee_flag": int(flag)
        }
        pipe_name = "618"
        # 删除缓存key
        redis_client.delete(redis_key)
        data = work_flow_cache_refresh(pipe_name, input_variable_values)
        if data is None:
            print(f"数据异常，记录执行异常代码{code}，收费标记：{flag}")
            error_code_list.append(code)
            continue
        print(f"{code}执行成功,收费标记：{flag}，记录缓存")
        redis_client.set(redis_key, date, ex=259200)


# ==============================
# 主执行函数
# ==============================
def execute_job():
    """主任务执行流程"""
    error_code_list = []
    print("开始执行任务")
    if not stock_list:
        print("股票列表为空，任务终止")
        return
    print("查询股票数量：" + str(len(stock_list)))
    # 2. 处理每只股票
    count = 0
    for stock in stock_list:
        count = count+1
        try:
            code = stock['code']
            print(f"处理第{count}只股票: Code={code},")
            executor_data_cache(code, error_code_list)
        except Exception as e:
            print("执行异常", e)
    if len(error_code_list) <= 200:
        print(f"任务执行完成")
    else:
        print(f"任务执行完成,执行失败代码:{str(error_code_list)}")
        # 存在异常代码，退出告警
        exit(1)


def remove_duplicates(stock_list, exclude_list):
    # 提取exclude_list中所有股票的code，用于快速查找
    exclude_codes = {item["code"] for item in exclude_list}
    # 过滤stock_list，只保留不在exclude_codes中的股票
    filtered_list = [item for item in stock_list if item["code"] not in exclude_codes]
    return filtered_list


# ==============================
# 程序入口
# ==============================
if __name__ == "__main__":
    # 获取所有股票
    # stock_list = [{"code": "AAPL", "market": 185}]
    all_stock_list = fetch_all_stock_list()
    spx_stock_list = fetch_spx_stock_list()
    stock_list = remove_duplicates(all_stock_list, spx_stock_list)

    # 1是强制刷新,0的时候不刷新
    forced_refresh_flag = "${forced_refresh}"
    # 收费免费标记
    fee_flag = "${fee_flag}"
    if fee_flag != "1" and fee_flag != "0" and fee_flag != "1,0":
        # 默认收费免费都跑
        fee_flag = "1,0"
    print(f"forced_refresh_flag is {forced_refresh_flag}")
    print(f"fee_flag is {fee_flag}")
    execute_job()
